package com.traffic.servlet;

import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理全局异常,controller中避免出现多个内部类
 * 
 * @author WANGQI
 * 
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    /**
     * 将所有异常信息通过JSON对象返回页面
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest reqest, HttpServletResponse response, Object obj,
            Exception exception) {
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            JSONObject json = Response.responseError(exception.getMessage());
            out.println(json);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
